//
//  LocationViewController.m
//  u76ho
//
//  Created by m-air-01 on 16/1/12.
//  Copyright © 2016年 LV. All rights reserved.
//

#import "LocationViewController.h"
#import "LocationSearchTableViewCell.h"
#import "SearchLocationViewController.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
@interface LocationViewController ()
<UITableViewDataSource,UITableViewDelegate,AMapLocationManagerDelegate,AMapSearchDelegate>
{
    UITableView * _tableView;
    NSMutableArray * _dataSource;
    
    NSMutableArray * selectedArr;
    
    AMapSearchAPI * _search;
}

@property (nonatomic, strong) AMapLocationManager *locationManager;

@end

@implementation LocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //高德地图
    [AMapLocationServices sharedServices].apiKey = AMPKey;
    
    self.locationManager = [[AMapLocationManager alloc]init];
    self.locationManager.delegate = self;
    
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    
    [self main];
    [self addItems];
    self.navigationItem.title =  @"所在位置";
    //[self addNavgationBar];
    // Do any additional setup after loading the view.
}

-(void)main
{
    [LoadingView loadingView];
    _dataSource = [[NSMutableArray alloc]init];
    selectedArr = [[NSMutableArray alloc]init];
    [selectedArr addObjectsFromArray:@[@"1"]];
    [_dataSource addObjectsFromArray:@[@"不显示位置"]];
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerNib:[UINib nibWithNibName:@"LocationSearchTableViewCell" bundle:nil] forCellReuseIdentifier:@"LocationSearchTableViewCell"];
    [self.view addSubview:_tableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    [AMapSearchServices sharedServices].apiKey = AMPKey;
    
    //初始化检索对象
    _search = [[AMapSearchAPI alloc]init];
    _search.delegate = self;

    
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            [LoadingView removeLoadingView];
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == 2)
            {
                return;
            }
        }
        
        NSLog(@"**********location:%@", location);
        
        
        //构造AMapPOIAroundSearchRequest对象，设置周边请求参数
        AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
        request.keywords = @"";
        if (regeocode)
        {
            
            //            NSLog(@"reGeocode:%@", regeocode);
            
            NSLog(@"%@",regeocode.formattedAddress);
            request.keywords = [NSString stringWithFormat:@"%@",regeocode.street];
        }
        
        // types属性表示限定搜索POI的类别，默认为：餐饮服务|商务住宅|生活服务
        // POI的类型共分为20种大类别，分别为：
        // 汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|
        // 医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
        // 交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
        request.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
        request.sortrule = 0;
        request.requireExtension = YES;
        
        //发起周边搜索
        [_search AMapPOIAroundSearch: request];
    }];
    


}


#pragma mark - 高德地图的代理回调
//实现POI搜索对应的回调函数
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    
   // NSLog(@"%d",response.pois.count);
    
    if(response.pois.count == 0)
    {
        return;
    }
    
    //通过 AMapPOISearchResponse 对象处理搜索结果
    NSString *strCount = [NSString stringWithFormat:@"count: %ld",(long)response.count];
    NSString *strSuggestion = [NSString stringWithFormat:@"Suggestion: %@", response.suggestion];
    NSString *strPoi = @"";
    for (AMapPOI *p in response.pois) {
        strPoi = [NSString stringWithFormat:@"%@\nPOI: %@", strPoi, p.description];
        if ([p.province isEqualToString:p.city]) {
            NSString * str = [NSString stringWithFormat:@"%@%@%@",p.city,p.district,p.address];
            if ([_dataSource containsObject:str]) {
                
            }
            else
            {
                [_dataSource addObject:str];
            }
        }
        else
        {
            NSString * str = [NSString stringWithFormat:@"%@%@%@%@",p.province,p.city,p.district,p.address];
            if ([_dataSource containsObject:str]) {
                
            }
            else
            {
                [_dataSource addObject:str];
            }
        }
        [selectedArr addObject:@"0"];
        NSLog(@"%@",p.name);
    }
    NSString *result = [NSString stringWithFormat:@"%@ \n %@ \n %@", strCount, strSuggestion, strPoi];
    NSLog(@"Place: %@", result);
    [LoadingView removeLoadingView];
    [_tableView reloadData];
}

#pragma mark - _tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count+1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        LocationSearchTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LocationSearchTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    static NSString * ID = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.textLabel.text = _dataSource[indexPath.row - 1];
    cell.textLabel.numberOfLines = 0;
    if ([selectedArr[indexPath.row-1] isEqualToString:@"1"]) {
        cell.textLabel.textColor = UIColorFromRGB(0x6EC844);
        UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
        imgV.image = [UIImage imageNamed:@"选中图标"];
        cell.accessoryView = imgV;
    }
    else
    {
        cell.textLabel.textColor = UIColorFromRGB(0x333944);
        cell.accessoryView = nil;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        SearchLocationViewController * searchLocationVC = [[SearchLocationViewController alloc]init];
        searchLocationVC.navigationItem.hidesBackButton = YES;
        [self.navigationController pushViewController:searchLocationVC animated:YES];
    }
    else
    {
        
        int i = (int)indexPath.row-1;
        for (int j = 0; j<selectedArr.count; j++) {
            if (i == j) {
                [selectedArr replaceObjectAtIndex:j withObject:@"1"];
            }
            else
            {
                [selectedArr replaceObjectAtIndex:j withObject:@"0"];
            }
        }
        [_tableView reloadData];
        
        

    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
#pragma mark - addItems
-(void)addItems
{
    UIButton * cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancleBtn.frame = CGRectMake(0, 0, 60, 30);
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn addTarget:self action:@selector(backItem:) forControlEvents:UIControlEventTouchUpInside];
    [cancleBtn setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc]initWithCustomView:cancleBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 40, 40);
    [rightBtn setTitle:@"确定" forState:UIControlStateNormal];
    [rightBtn setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(makeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}
-(void)makeBtnAction:(UIButton *)btn
{
    for (int i = 0; i<selectedArr.count; i++) {
        if ([[selectedArr objectAtIndex:i] isEqualToString:@"1"]) {
            if (i == 0) {
                [self.delegate locationDelegateWithStr:@""];
            }
            else
            {
                [self.delegate locationDelegateWithStr:_dataSource[i]];
            }
        }
        
    }

    [self.navigationController popViewControllerAnimated:YES];
}
-(void)backItem:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
    //    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
